import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';


class MyWebPage extends StatefulWidget {
  @override
  _MyWebPageState createState() => _MyWebPageState();
}

class _MyWebPageState extends State<MyWebPage> {

  // final Completer<WebViewController> webController = Completer<WebViewController>();
  bool webViewReady = false;
  WebViewController? actController;
  String webUrl = "images/index.html";
  String title = "看视频";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text(title),
    ),
    body: WillPopScope(
      child: _mainBody(context),
      onWillPop: ()async {
        _backClick();
        return Future.value(false);
      },
    ),
    );
  }

  /// 顶部topBar
  Widget _topBar(){
    return FutureBuilder<WebViewController>(
      // future: webController.future,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
        webViewReady = snapshot.connectionState == ConnectionState.done;
        actController = snapshot.data;
        return Stack(
          alignment: Alignment.center,
          children: [
            Row(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[

                ListTile(
                  leading: Icon(Icons.arrow_back),
                  onTap: (){
                    _backClick();
                  },
                ),

                ListTile(
                  leading: Icon(Icons.close),
                  onTap: (){
                    if(webViewReady) {
                      _backClick(isClose: true);
                    }
                  },
                ),

                Expanded(
                  child: Text(''),
                ),

                // IconButton(
                //   icon: const Icon(Icons.replay, color: AppColor.c333333,),
                //   onPressed: !webViewReady
                //       ? null
                //       : () {
                //     actController!.reload();
                //   },
                // ),
              ],
            ),

            Container(

              child: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,),
            ),
          ],
        );
      },
    );
  }



  /// 主体
  Widget _mainBody(BuildContext context){
    return /*Expanded(
      flex: 1,
      child: */WebView(
        initialUrl: webUrl,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          // webController.complete(webViewController);
        },
        onProgress: (int progress) {
          print("WebView is loading (progress : $progress%)");
          // controller.setProgress(progress);
        },
        javascriptChannels: <JavascriptChannel>{
          /// js调用Flutter方法
          _getApkDownloadProgress(context),
        },
        navigationDelegate: (NavigationRequest request) {
          // if (request.url.startsWith('https://www.youtube.com/')) {
          //   print('blocking navigation to $request}');
          //   return NavigationDecision.prevent;
          // }
          print('allowing navigation to $request');
          return NavigationDecision.navigate;
        },
        onPageStarted: (String url) {
          print('Page started loading: $url');
          // controller.setShowProgress(true);
          // if(url.startsWith(SchemeKey.WELFARE_GAME) || url.startsWith(SchemeKey.PLAY_GAME)){
          //   controller.toScheme(url);
          //   return;
          // }
        },
        onPageFinished: (String url) {
          print('Page finished loading: $url');
          // controller.setShowProgress(false);
        },
        gestureNavigationEnabled: true,
      /*),*/
    );
  }

  /// js调用Flutter方法----------------------------------start----------------------------------

  JavascriptChannel _getApkDownloadProgress(BuildContext context) {
    return JavascriptChannel(
        name: 'messageHandler',
        onMessageReceived: (JavascriptMessage message) {
          print('JavascriptChannel:'+message.message);
          int progressNum = 30;
          _sendToJs("fromFlutter", '$progressNum');
        });
  }

  /// Flutter调用js方法----------------------------------start----------------------------------

  _sendToJs(String methodName, String jsonData) async {
    String jsStr = '$methodName($jsonData)';
    print('jsStr:'+jsStr);
    await actController?.runJavascript(jsStr);
    // await actController?.runJavascriptReturningResult("").then((res){
    //   AppLog.d(methodName+","+res.toString());
    // });
  }


  /// 点击返回
  _backClick({bool? isClose}) async {
    if(isClose!=null && isClose){
      Navigator.pop(context);/// 关闭页面
      return;
    }
    if (await actController!.canGoBack()) {
      await actController?.goBack();/// 网页返回上一页
    } else {
      Navigator.pop(context);/// 关闭页面
    }
  }


  
}